#!/usr/bin/env bash
# generate expire time in python: time.mktime((2012, 5, 1, 0, 0, 0, 0, 0, -1))
#    -DAPP_EXPIRE_TIME=1364796000 \
set -e

if [ -z "$O3" ]; then
    echo O3 var must point to ovpn3 tree
    exit 1
fi

cd $O3/core
. vars/android-sdk-path
cd javacli
git clean -q -fXd .

if [ "$PKG" ]; then
    pkg=$PKG
    pkg_id_def="-DOPENVPN_PACKAGE_ID=${PKG//./_}"
else
    pkg=net.openvpn.openvpn
    pkg_id_def="-DOPENVPN_PACKAGE_ID=net_openvpn_openvpn"
fi
echo PACKAGE $PKG

if [ "$PT_PROXY" = "1" ] && [ -d "$O3/common" ]; then
    common="-I$O3/common -DPRIVATE_TUNNEL_PROXY"
else
    common=""
fi

echo SWIG
swig -c++ -java -package $pkg -I$O3/core/client -I$O3/core ovpncli.i

TARGETS=${TARGETS:-android-a7a android-a8a android-x86}

for TARGET in $TARGETS; do

if [ "$DEBUG_BUILD" = "1" ]; then
    . ../vars/vars-${TARGET}-dbg
    vis1=""
    vis2=""
    opt2="$pkg_id_def $LIB_OPT_LEVEL"
else
    . ../vars/vars-${TARGET}
    vis1="-fvisibility=hidden"
    vis2='-DSWIGEXPORT=__attribute__((visibility("default")))'
    opt2="$pkg_id_def -Os"
fi

if [ "$OPENSSL" = "1" ]; then
    ssl_def="-DUSE_OPENSSL"
    ssl_inc="-I$DEP_DIR/openssl/openssl-$PLATFORM/include"
    ssl_lib="-lssl -lcrypto"
    ssl_libdir="-L$DEP_DIR/openssl/openssl-$PLATFORM/lib"
else
    ssl_def="-DUSE_MBEDTLS"
    ssl_inc="-I$DEP_DIR/mbedtls/mbedtls-$PLATFORM/include"
    ssl_lib="-lmbedtls"
    ssl_libdir="-L$DEP_DIR/mbedtls/mbedtls-$PLATFORM/library"
fi

[ -z "$GPP_CMD" ] && GPP_CMD=g++

echo CORE $ABI
$GPP_CMD \
    $CXX_COMPILER_FLAGS \
    $PLATFORM_FLAGS \
    $OTHER_COMPILER_FLAGS \
    $LIB_OPT_LEVEL $LIB_FPIC \
    -Wall -Wno-sign-compare -Wno-unused-parameter \
    -Wno-unused-local-typedefs \
    $vis1 \
    $ssl_def \
    -DUSE_ASIO \
    -DASIO_STANDALONE \
    -DASIO_NO_DEPRECATED \
    -DHAVE_LZ4 \
    -DOPENVPN_USE_TLS_MD5 \
    -I$O3/core/client \
    -I$O3/core \
    $common \
    -I$DEP_DIR/asio/asio/include \
    $ssl_inc \
    -I$DEP_DIR/lz4/lz4-$PLATFORM/include \
    -c $O3/core/client/ovpncli.cpp

echo WRAP $ABI
$GPP_CMD \
    $CXX_COMPILER_FLAGS \
    $PLATFORM_FLAGS \
    $OTHER_COMPILER_FLAGS \
    $opt2 $LIB_FPIC \
    -fno-strict-aliasing \
    -Wall \
    $vis1 $vis2 \
    -I$O3/core/client \
    -I$O3/core \
    $common \
    $ssl_libdir \
    -L$DEP_DIR/lz4/lz4-$PLATFORM/lib \
    ovpncli_wrap.cxx \
    android/jellybean_hack.cpp \
    android/cpu.cpp \
    ovpncli.o \
    -o libovpncli.so \
    -shared -Wl,-soname,libovpncli.so \
    $ssl_lib \
    -llz4 \
    -llog

if [ "$DEBUG_BUILD" != "1" ]; then
    echo STRIP $ABI
    strip libovpncli.so
fi

mkdir -p build/libs/$ABI
mv libovpncli.so build/libs/$ABI/
rm ovpncli.o
done

mv ovpncli_wrap.cxx ovpncli_wrap.h ovpncli.java ovpncliJNI.java SWIGTYPE_*.java ClientAPI_*.java build/
git clean -q -fX .

tar -czf android-core-build.tgz build
mv android-core-build.tgz $O3/
